import psutil
import time
import os

def clear_screen():
    """清屏，兼容Linux"""
    os.system('clear')

def process_manager():
    """进程管理主函数"""
    processes = []
    filtered_processes = []
    stats = {}
    current_page = 0
    max_page_size = 30
    filter_type = "显示全部"
    search_text = ""

    def collect_processes():
        """采集进程信息"""
        nonlocal processes, stats
        processes = []
        stats = {'total': 0, 'running': 0, 'sleeping': 0, 'zombie': 0, 'stopped': 0,
                 'high_cpu': 0, 'high_memory': 0, 'suspicious': 0}

        try:
            for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info', 'status']):
                try:
                    info = proc.info
                    memory_mb = info['memory_info'].rss / (1024 ** 2) if info['memory_info'] else 0
                    cpu_percent = info['cpu_percent'] or 0

                    process_info = {
                        'pid': info['pid'],
                        'name': info['name'] or f"PID-{info['pid']}",
                        'cpu_percent': cpu_percent,
                        'memory_mb': memory_mb,
                        'status': info['status'] or 'unknown'
                    }

                    processes.append(process_info)

                    stats['total'] += 1
                    status = process_info['status']
                    if status in stats:
                        stats[status] += 1
                    if cpu_percent > 50:
                        stats['high_cpu'] += 1
                    if memory_mb > 200:
                        stats['high_memory'] += 1
                    if cpu_percent > 80 or memory_mb > 1000:
                        stats['suspicious'] += 1

                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    continue
        except Exception as e:
            print(f"采集进程信息失败: {e}")
        return processes, stats

    def filter_processes():
        """应用过滤条件"""
        nonlocal filtered_processes
        filtered_processes = processes.copy()

        if search_text:
            filtered_processes = [p for p in filtered_processes
                                if search_text in str(p['pid']) or search_text.lower() in p['name'].lower()]

        if filter_type == "高CPU占用":
            filtered_processes = [p for p in filtered_processes if p.get('cpu_percent', 0) > 30]
        elif filter_type == "高内存占用":
            filtered_processes = [p for p in filtered_processes if p.get('memory_mb', 0) > 100]

    def display_processes():
        """显示进程列表"""
        clear_screen()
        print("=" * 80)
        print("进程管理")
        print("=" * 80)
        print(f"总进程数: {stats['total']} | 运行中: {stats['running']} | 异常进程: {stats['suspicious']} | 高CPU占用: {stats['high_cpu']}")
        print(f"当前过滤: {filter_type} | 搜索: {search_text or '无'}")
        print("-" * 80)

        total_pages = max(1, (len(filtered_processes) + max_page_size - 1) // max_page_size)
        start_idx = current_page * max_page_size
        end_idx = min(start_idx + max_page_size, len(filtered_processes))
        displayed = filtered_processes[start_idx:end_idx]

        print(f"{'PID':<8} {'进程名':<30} {'CPU(%)':<10} {'内存(MB)':<12} {'状态':<10}")
        print("-" * 80)
        for proc in displayed:
            status_display = get_status_display(proc.get('status', 'unknown'))
            print(f"{proc['pid']:<8} {proc['name'][:28]:<30} {proc['cpu_percent']:<10.1f} {proc['memory_mb']:<12.1f} {status_display:<10}")
        print("-" * 80)
        print(f"第 {current_page + 1} 页 / 共 {total_pages} 页")
        print("\n操作: [r] 刷新 | [s] 搜索 | [f] 过滤 | [t] 终止进程 | [p] 上一页 | [n] 下一页 | [q] 返回")

    def get_status_display(status):
        """获取状态显示名称"""
        status_map = {
            'running': '运行', 'sleeping': '休眠', 'disk-sleep': '磁盘休眠',
            'stopped': '停止', 'zombie': '僵尸', 'dead': '死亡'
        }
        return status_map.get(str(status), '未知')

    def terminate_process(pid):
        """终止进程"""
        try:
            process = psutil.Process(pid)
            process_name = process.name()
            process.terminate()
            print(f"进程 {process_name} (PID: {pid}) 已终止")
        except Exception as e:
            print(f"终止进程失败: {e}")
        input("\n按 Enter 继续...")

    while True:
        processes, stats = collect_processes()
        filter_processes()
        display_processes()

        choice = input("请输入操作: ").lower()
        if choice == 'q':
            break
        elif choice == 'r':
            continue
        elif choice == 's':
            search_text = input("请输入搜索关键词（PID或进程名）: ")
            current_page = 0
        elif choice == 'f':
            print("\n过滤选项: [1] 显示全部 | [2] 高CPU占用 | [3] 高内存占用")
            filter_choice = input("请选择过滤类型 (1-3): ")
            filter_map = {"1": "显示全部", "2": "高CPU占用", "3": "高内存占用"}
            filter_type = filter_map.get(filter_choice, "显示全部")
            current_page = 0
        elif choice == 't':
            pid_input = input("请输入要终止的进程 PID: ")
            try:
                pid = int(pid_input)
                terminate_process(pid)
            except ValueError:
                print("无效的 PID，请输入数字")
                input("\n按 Enter 继续...")
        elif choice == 'p':
            if current_page > 0:
                current_page -= 1
        elif choice == 'n':
            total_pages = max(1, (len(filtered_processes) + max_page_size - 1) // max_page_size)
            if current_page < total_pages - 1:
                current_page += 1
        else:
            print("无效操作，请重试")
            input("\n按 Enter 继续...")